/**   
 * @Title: HttpConnectionCall.java 
 * @Package cn.com.gome.commons.rpc.httpcon 
 * @Description: httpconnection调用
 * @author chenmin-ds   
 * @date 2016年2月22日 上午11:57:52 
 * @company cn.com.gome
 * @version V1.0   
 */

package cn.com.gome.commons.rpc.httpcon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;


/**
 * @ClassName: HttpConnectionCall
 * @Description: httpconnection调用
 * @author chenmin-ds
 * @date 2016年2月22日 上午11:57:52
 */
public class HttpConnectionCall {
	
	private static Logger log = LoggerFactory.getLogger("HttpConnectionCall");

	public static String charSet = "UTF-8";

	public static int GET = 1;

	public static int POST = 2;

	public static String STATUS_200 = "200";

	public static String STATUS_201 = "201";

	public static String STATUS_202 = "202";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static String call(String url, String charSetV, int method, Map<String, String> info) {
		if (method == GET) {
			StringBuffer sb = new StringBuffer();
			sb.append(url);
			if (!url.endsWith("?")) {
				sb.append("?");
			}
			if (null != info) {
				Iterator iterator = info.entrySet().iterator();
				Entry<String, String> entry = null;
				while (iterator.hasNext()) {
					entry = (Entry<String, String>) iterator.next();
					sb.append(entry.getKey() + "=" + entry.getValue() + "&");
				}
				String temp = sb.toString();
				if (!url.endsWith("&")) {
					url = temp.substring(0, temp.length() - 1);
				} else {
					url = temp;
				}
			}
			return callGet(url, charSetV);
		} else {
			return callPost(url, charSetV, info);
		}
	}

	private static String callGet(String url, String charSetV) {
		HttpURLConnection connection = null;
		String content = "";
		try {
			URL address_url = new URL(url);
			connection = (HttpURLConnection) address_url.openConnection();
			connection.setRequestMethod("GET");
			connection.setConnectTimeout(10000);
			connection.setReadTimeout(10000);
			connection.setRequestProperty("contentType", charSetV);
			connection.connect();
			// 得到访问页面的返回值
			int response_code = connection.getResponseCode();
			log.info("访问url状态：response_code={}", response_code);
			if (response_code == HttpURLConnection.HTTP_OK) {
				InputStream in = connection.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String line = null;
				StringBuffer sb = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				return "200:"+sb.toString();
			}else if(response_code == 302){
				content = "200:请求被重定向，response_code" + response_code;
			} else {
				content = "201:调用失败，response_code" + response_code;
			}
		} catch (Exception e) {
			content = "202:调用异常，" + e.getMessage();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return content;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static String callPost(String url, String charSetV , Map<String, String> info) {
		HttpURLConnection connection = null;
		String content = "";
		try {
			URL address_url = new URL(url);
			connection = (HttpURLConnection) address_url.openConnection();
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(3000);
			connection.setRequestProperty("contentType", charSetV);
			connection.connect();
			
		    // 表单参数与get形式一样
			StringBuffer params = new StringBuffer();
			if(null != info && info.size() > 0){
				Iterator iterator = info.entrySet().iterator();
				Entry<String,String> entry = null;
				while(iterator.hasNext()){
					entry = (Entry<String, String>) iterator.next();
					params.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
				}
				String p = params.toString();
				p = p.substring(0, p.length()-1);
				byte[] bypes = p.getBytes();
				connection.getOutputStream().write(bypes);// 输入参数
			}
			
			// 得到访问页面的返回值
			int response_code = connection.getResponseCode();
			if (response_code == HttpURLConnection.HTTP_OK) {
				InputStream in = connection.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				String line = null;
				StringBuffer sb = new StringBuffer();
				while ((line = reader.readLine()) != null) {
					sb.append(line);
				}
				return "200:"+sb.toString();
			}else if(response_code == 302){
				content = "200:请求被重定向，response_code" + response_code;
			} else {
				content = "201:调用失败,response_code=" + response_code;
			}
		} catch (Exception e) {
			content = "202:调用异常，" + e.getMessage();
		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return content;
	}
	


}
